package com.me.study.app.rvRichEditor

import com.chad.library.adapter.base.BaseProviderMultiAdapter
import com.me.study.app.data.NotifyType
import com.me.study.app.data.RichEditorType
import com.me.study.app.rvRichEditor.listener.EditorCursorListener
import com.me.study.app.rvRichEditor.listener.EditorTouchListener
import com.me.study.app.rvRichEditor.provider.RichEditorImageProvider
import com.me.study.app.rvRichEditor.provider.RichEditorTestProvider
import com.me.study.app.rvRichEditor.provider.RichEditorTextProvider
import com.me.study.app.rvRichEditor.provider.RichEditorVideoProvider

/**
 *create author : FZW
 *create date  : 2024/9/18
 */
class RichEditorAdapter(
    listener: EditorTouchListener,
    listenerCursor: EditorCursorListener
) : BaseProviderMultiAdapter<RichEditorData>() {

    init {
        addItemProvider(RichEditorTestProvider())
        addItemProvider(RichEditorTextProvider(listenerCursor))
        addItemProvider(RichEditorImageProvider(listener))
        addItemProvider(RichEditorVideoProvider(listener))
    }

    override fun getItemType(data: List<RichEditorData>, position: Int): Int {
        return data[position].type
    }

    fun getTestData(): ArrayList<RichEditorData> {
        val list = arrayListOf<RichEditorData>()
        for (item in 1..20) {
            list.add(
                RichEditorData(
                    RichEditorType.TEST.VALUE, "$item", "",
                    isMove = false,
                    isFocusable = false
                )
            )
        }
        return list
    }

    fun actionAddImage(position: Int): Boolean {
        if (position < 0 || position >= data.size) {
            return false
        }
        val editorData = data[position]
        if (editorData.type == RichEditorType.TEXT.VALUE) {
            return editorData.s1.isNotEmpty()
        }
        return false
    }

    fun onMove(sourcePosition: Int, targetPosition: Int) {
        val item = data[sourcePosition]
        data.removeAt(sourcePosition)
        data.add(targetPosition, item)
        notifyItemMoved(sourcePosition, targetPosition)
//        notifyDataSetChanged()
    }

    fun startMoveText() {
        for ((position, item) in data.withIndex()) {
            if (item.type == RichEditorType.TEXT.VALUE) {
                item.isMove = true
                notifyItemChanged(position, NotifyType.START_MOVE.VALUE)
            }
        }
    }

    fun endMoveText() {
        for ((position, item) in data.withIndex()) {
            if (item.type == RichEditorType.TEXT.VALUE) {
                item.isMove = false
                notifyItemChanged(position, NotifyType.END_MOVE.VALUE)
            }
        }
    }

}